package org.com.ashen.web.controller.sys;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import okhttp3.*;
import org.apache.log4j.Logger;
import org.com.ashen.common.common.HttpResult;
import org.com.ashen.service.util.FileUtil;
import org.com.ashen.web.constant.CommonUtils;
import org.com.ashen.web.constant.UrlConstant;
import org.com.ashen.web.weimeng.uploadImg.UploadImgInParam;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.util.UUID;

@Controller
public class ExecuteSqlController {

	private static Logger logger = Logger.getLogger(ExecuteSqlController.class.getName());



	@RequestMapping(value = UrlConstant.UPLOADIMG, produces = CommonUtils.CONTENT_TYPE)
	@ResponseBody
	public String executeUploadPic(final HttpServletRequest request, final HttpServletResponse response,String injson,String signtype) {
		String serverPathtemp = request.getSession().getServletContext().getRealPath("").substring(0,request.getSession().getServletContext().getRealPath("").length()-1);
		String serverPath = request.getSession().getServletContext().getRealPath("").substring(0, serverPathtemp.length() - serverPathtemp.substring(serverPathtemp.lastIndexOf("\\")+1).length());
		String relativePath = "files\\";
		String dirPath = serverPath+ relativePath;
		UploadImgInParam uploadImgInParam = JSON.parseObject(injson, UploadImgInParam.class);
		if (signtype.equals("weimeng")) {
			try {
				
				OkHttpClient okHttpClient = new OkHttpClient();
			    Request request2 = new Request.Builder()
			            .url(uploadImgInParam.getFile())
			            .build();
			    Response response2 = okHttpClient.newCall(request2).execute();
			    byte[] bytes = response2.body().bytes();
			    String picName = uploadImgInParam.getName();
				File dir = new File(dirPath);
				if (!dir.exists()) {
					dir.mkdirs();
				}
				String subFixStr =  picName.substring(picName.lastIndexOf(".")+1);
				String picname = UUID.randomUUID().toString()+ "_d."+subFixStr;
				String destPath = dirPath + picname;
				logger.error(destPath);
				MediaType MEDIA_TYPE_PNG = MediaType.parse("image/"+subFixStr);
				// 真正写到磁盘上
				File file = new File(destPath);
				FileOutputStream fos = new FileOutputStream(file);
				BufferedOutputStream bos = new BufferedOutputStream(fos);
	            bos.write(bytes);
	            bos.close();
	            fos.close();
	            RequestBody fileBody = RequestBody.create(MEDIA_TYPE_PNG, file);
		        RequestBody requestBody = new MultipartBody.Builder()
		                .setType(MultipartBody.FORM)
		                .addFormDataPart("file", "aa", fileBody)
		                .addFormDataPart("name", picName)
		                .build();
		        String JsonString = FileUtil.getFileContent(CommonUtils.FILE_PATH);
				JSONObject jsonObject = JSON.parseObject(JsonString);
				String access_token = jsonObject.getString("weimengAccessToken");
				String url = "https://dopen.weimob.com/media/1_0/ec/goodsImage/uploadImg?accesstoken="+ access_token;
				OkHttpClient client = new OkHttpClient();
				Request req = new Request.Builder().addHeader("charset", "utf-8")
			                .url(url)
			                .post(requestBody)
			                .build();
				Response respon = client.newCall(req).execute();
				file.delete();
				return respon.body().string();
			}catch (Exception e) {
				String errString = HttpResult.failedResultRtn(e.getMessage(), "").toString();
				return errString.replace("\\\"", "\"").replace("\"[", "[").replace("]\"", "]").replace("\"{", "{").replace("}\"", "}");
			}
		}
		return null;
	}


	
	@RequestMapping(value = UrlConstant.UPLOADVIDEO, produces = CommonUtils.CONTENT_TYPE)
	@ResponseBody
	public String uploadVideo(final HttpServletRequest request, final HttpServletResponse response,String injson,String signtype) {
		String serverPathtemp = request.getSession().getServletContext().getRealPath("").substring(0,request.getSession().getServletContext().getRealPath("").length()-1);
		String serverPath = request.getSession().getServletContext().getRealPath("").substring(0, serverPathtemp.length() - serverPathtemp.substring(serverPathtemp.lastIndexOf("\\")+1).length());
		String relativePath = "files\\";
		String dirPath = serverPath+ relativePath;
		UploadImgInParam uploadImgInParam = JSON.parseObject(injson, UploadImgInParam.class);
		if (signtype.equals("weimeng")) {
			try {
				
				OkHttpClient okHttpClient = new OkHttpClient();
			    Request request2 = new Request.Builder()
			            .url(uploadImgInParam.getFile())
			            .build();
			    Response response2 = okHttpClient.newCall(request2).execute();
			    byte[] bytes = response2.body().bytes();
			    String picName = uploadImgInParam.getName();
				File dir = new File(dirPath);
				if (!dir.exists()) {
					dir.mkdirs();
				}
				String subFixStr =  picName.substring(picName.lastIndexOf(".")+1);
				String picname = "_d."+subFixStr;
				String destPath = dirPath + picname;
				logger.error(destPath);
				MediaType MEDIA_TYPE_PNG = MediaType.parse("video/"+subFixStr);
				// 真正写到磁盘上
				File file = new File(destPath);
				FileOutputStream fos = new FileOutputStream(file);
				BufferedOutputStream bos = new BufferedOutputStream(fos);
	            bos.write(bytes);
	            bos.close();
	            fos.close();
	            
	            RequestBody fileBody = RequestBody.create(MEDIA_TYPE_PNG, file);
		        RequestBody requestBody = new MultipartBody.Builder()
		                .setType(MultipartBody.FORM)
		                .addFormDataPart("file", "aa", fileBody)
		                .addFormDataPart("name", picName)
		                .build();
		        String JsonString = FileUtil.getFileContent(CommonUtils.FILE_PATH);
				JSONObject jsonObject = JSON.parseObject(JsonString);
				String access_token = jsonObject.getString("weimengAccessToken");
				String url = "https://dopen.weimob.com/media/1_0/ec/goodsVideo/uploadVideo?accesstoken="+ access_token;
				OkHttpClient client = new OkHttpClient();
				Request req = new Request.Builder().addHeader("charset", "utf-8")
			                .url(url)
			                .post(requestBody)
			                .build();

				Response respon = client.newCall(req).execute();
				return respon.body().string();
			}catch (Exception e) {
				String errString = HttpResult.failedResultRtn(e.getMessage(), "").toString();
				return errString.replace("\\\"", "\"").replace("\"[", "[").replace("]\"", "]").replace("\"{", "{").replace("}\"", "}");	
			}
		}
		return null;
			
	}

}